#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/16 16:32
# @Author  : ningbo
# @File    : mes.py
# @Software: python3.7

import json
import requests
import sys

HEADER = {'Content-Type': 'application/json; charset=utf-8',
          'x-request-datasource': '101',
          'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'
          }

config = {}
with open("config.json", "r") as f:
    config = json.load(f)
username = config["username"]
password = config["password"]
workStation = config["workStation"]
workStationCode = config["workStationCode"]


def login(username, password, workStation, workStationCode):
    r1 = requests.post(
        "http://192.168.8.34:8950/api/station/login?username={}&password={}&workStation={}&workStationCode={}&barcode=&sob=101".format(
            username, password, workStation, workStationCode), headers=HEADER)
    r2 = requests.post(
        "http://192.168.8.34:8950/api/station/login?username={}&password={}&workStation={}&workStationCode={}&barcode=&sob=101".format(
            username, password, workStation, workStationCode), headers=HEADER, cookies=r1.cookies)
    if r2.json()["message"] == "ok":
        return r1.cookies
    else:
        print(r2.json()["message"])
        # input("登录失败,按回车退出程序：")
        return "-1"


def feed(sn, sonSN, cookies, workStation, tag):     # 上料
    r3 = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/get/parentSn/info?barcode={}".format(sn),
                       headers=HEADER, cookies=cookies)
    if r3.status_code == 200 and "账号密码登陆" in r3.text:
        print("登录超时,请重启软件！")
        # input("按回车退出程序：")
        return "-1"
    if r3.status_code == 200 and r3.json()["state"] == "-1":
        print(r3.json()["msg"])
        return "-1"
    parentData = r3.json()['resBody']  # 查询父部件的条码信息
    barcode = parentData['barcode']
    srcDocNo = parentData['srcDocNo']
    resBody = {
        "operator": username, "operateTime": "", "workStation": workStation,
        "reqBody": srcDocNo
    }
    r1 = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/get/order", headers=HEADER, cookies=cookies,
                       json=resBody)
    if r1.json()["state"] == "-1":
        print(r1.json()["msg"])
        # input("上料失败,按回车退出程序：")
        return "-1"
    rowNum = r1.json()["resBody"][0]['rowNum']
    r4 = requests.post(
        "http://192.168.8.34:8950/r9-mes/api/work/workOrder/feed/get/inv?barcode={}&rowNum=".format(sonSN, rowNum),
        headers=HEADER, cookies=cookies)
    if r4.status_code == 200 and "账号密码登陆" in r4.text:
        print("登录超时,请重启软件！")
        # input("按回车退出程序：")
        return "-1"
    if r4.status_code == 200 and r4.json()["state"] == "-1":
        print(r4.json()["msg"])
        return "-1"
    sonData = r4.json()['resBody']  # 查询子部件物料信息
    body = {"operator": username, "operateTime": "", "workStation": workStation,
            "reqBody": {"workStationId": workStation,
                        "deviceCode": "",
                        "rowNum": rowNum,
                        "ioCategory": "收货",
                        "invCode": sonData['invCode'],
                        "invName": sonData['invName'],
                        "invSpec": sonData['invSpec'],
                        "invClassCode": "",
                        "invClassName": "",
                        "quantity": sonData['quantity'],
                        "barcodeInitialQty": "1",
                        "packageNo": "",
                        "projectNo": "",
                        "parentBarcode": barcode,
                        "parentSn": sn,
                        "parentBomId": "",
                        "sn": sonData['sn'],
                        "batchNumber": "",
                        "massDate": "",
                        "massUnit": "",
                        "dmDate": "",
                        "dvDate": "",
                        "barcode": sonData["barcode"],
                        "invReturnDate": None,
                        "supplierCode": "",
                        "operator": username,
                        "isConfirm": False,
                        "cdefine1": ""}}
    r_save = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/feed/save", headers=HEADER,
                           cookies=cookies, json=body)
    if r_save.json()["state"] == "1":
        print("{}上料完成......".format(tag), end="")
    elif r_save.json()["state"] == "-1":
        print(r_save.json()["msg"])
        return "-1"
    else:
        # input("上料失败,按回车退出程序：")
        return "-1"


def complete(username, sn, cookies, workStation):       # 报工
    r2 = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/get/parentSn/info?barcode={}".format(sn),
                       headers=HEADER, cookies=cookies)
    barcode = r2.json()["resBody"]["barcode"]
    srcDocNo = r2.json()["resBody"]['srcDocNo']
    resBody = {
        "operator": username, "operateTime": "", "workStation": workStation,
        "reqBody": {"barcode": srcDocNo, "workStation": workStation}
    }
    r1 = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/complete", headers=HEADER, cookies=cookies,
                       json=resBody)
    if r1.json()["state"] == "-1":
        print(r1.json()["msg"])
        # input("报工失败,按回车退出程序：")
        return "-1"
    rowNum = r1.json()["resBody"][0]['rowNum']
    body = {"operator": username, "operateTime": "", "workStation": workStation,
            "reqBody": {"rowNum": rowNum, "workStation": workStation, "sn": sn,
                        "singleBarcode": barcode, "deviceCode": "", "type": "手动", "quantity": "1",
                        "unQualifiedQty": "0", "badQty": "0", "badReason": "", "badReasonSelect": "",
                        "nextEmployee": "",
                        "dutyCompleteDetail": "", "workTime": "0", "singleWeight": "", "totalWeight": "",
                        "completeEmpCode": username, "packageNo": "", "cameraFile": "[]", "paramList": []}}
    r3 = requests.post("http://192.168.8.34:8950/r9-mes/api/work/workOrder/complete/save", headers=HEADER,
                       cookies=cookies, json=body)
    if r3.json()["state"] == "1":
        print("报工完成")
    elif r3.json()["state"] == "-1":
        print(r3.json()["msg"])
    else:
        return "-1"


if __name__ == '__main__':
    try:
        cookies = login(username, password, workStation, workStationCode)
    except Exception as e:
        input("网络故障,按回车退出程序：")
        sys.exit(-1)

    while True:
        sn = input("请输入父部件的sn号：").strip()
        sonSN = input("请输入子部件的sn号：").strip()
        print("{}......{}......{}......".format(username, sn, sonSN), end='')
        if sn == sonSN:
            if feed(sn, sn, cookies, workStation, "父部件") == "-1":
                continue
        else:
            if feed(sn, sn, cookies, workStation, "父部件") == "-1":
                continue
            if feed(sn, sonSN, cookies, workStation, "子部件") == "-1":
                continue
        if complete(username, sn, cookies, workStation) == "-1":
            continue
